#pragma once
#include <string>
#include <functional>
#include "Epoller.hpp"
#include "TcpServer.hpp"
#include "Log.hpp"

class Connection;
class TcpServer;
using func_t = std::function<void(Connection *)>;

class Connection
{
public:
    Connection(int sockfd, uint32_t event, TcpServer *R)
        : _sockfd(sockfd), _event(event), _R(R)
    {
    }

    // 用来注册回调
    void RegisterCallBack(func_t recver, func_t sender, func_t excepter)
    {
        _recver = recver;
        _sender = sender;
        _excepter = excepter;
    }
    ~Connection()
    {
    }
    void AddInbuffer(const std::string & message)
    {
        _inbuffer+=message;
    }


    void AddOutbuffer(const std::string & message)
    {
        _outbuffer+=message;
    }
    int GetConnFd()
    {
        return _sockfd;
    }

    void SetEvent(uint32_t event)
    {
        _event = event;
    }

    uint32_t Event()
    {
        return _event;
    }

    std::string &GetInbuffer()
    {
        return _inbuffer;
    }

    std::string & GetOutbuffer()
    {
        return _outbuffer;
    }

    bool IsOutbufferEmpty()
    {
        return _outbuffer.empty();
    }

public:
    int _sockfd;

    std::string _inbuffer;
    std::string _outbuffer;

    uint32_t _event;

public:
    // 回调的方法
    func_t _recver;
    func_t _sender;
    func_t _excepter;

    TcpServer *_R;
};

class ConnectionFactory
{
public:
    static Connection *BulidListenConnection(int listensock, func_t recver, uint32_t event, TcpServer *R)
    {
        Connection * conn=new Connection(listensock,event,R);
        //listen sock只关心读
        conn->RegisterCallBack(recver,nullptr,nullptr);
        
        return conn;
    }

    static Connection *BulidNormalConnction(int sockfd,func_t recver,func_t sender,func_t excepter,uint32_t event,TcpServer *R)
    {
        //创建连接，关心什么事件
        Connection* normal_conn=new Connection(sockfd,event,R);
        normal_conn->RegisterCallBack(recver,sender,excepter);

        return normal_conn;
    }
};